/**
 * Created by jiachneyu on 2018/4/20.
 */
const {pub, pubUpdate, remove} = require("../model/blog/admin");
const md5 = require("md5")

const pubData = async (ctx, next) => {
    console.log(ctx.request.body)
    if (ctx.request.body._id) {
        await pubUpdate(ctx.request.body).then(res => {
            console.log(res)
            let returnJson = {};
            if (res.code === 1) {
                returnJson = {
                    ...res,
                    msg: "保存成功"
                }
            }
            else {
                returnJson = {
                    code: -1,
                    msg: "保存失败，请重试"
                }
            }
            ctx.body = returnJson;
        })
    }
    else {
        await pub(ctx.request.body).then(res => {
            console.log(res)
            let returnJson = {};
            if (res.code === 1) {
                returnJson = {
                    ...res,
                    msg: "发布成功"
                }
            }
            else {
                returnJson = {
                    code: -1,
                    msg: "发布失败，请重试"
                }
            }
            ctx.body = returnJson;
        });
    }
}


const removeArt = async (ctx, next) => {
    await remove(ctx.request.body).then(res => {
        console.log(res)
        let returnJson = {};
        if (res.code === 1) {
            returnJson = {
                ...res,
                msg: "删除成功"
            }
        }
        else {
            returnJson = {
                code: -1,
                msg: "删除失败，请重试"
            }
        }
        ctx.body = returnJson;
    })
}

const getAlive = (ctx)=>{
    const cid = ctx.cookies.get("cid")
    const trueCid = md5(`jcyjiachenyujiachenyu`);
    if(cid === trueCid){
        ctx.body = {
            code: 1
        }
    }
    else {
        ctx.body = {
            code: -1
        }
    }
}

module.exports = [
    {
        method: "post",
        path: "/api/blog/pub",
        handle: pubData
    },
    {
        method: "post",
        path: "/api/blog/removeArticle",
        handle: removeArt
    },
    {
        method: "post",
        path: "/api/admin/alive",
        handle: getAlive
    }
]